package com.ftqh.core.web.controller;

import com.ftqh.core.jpa.domain.AbstractDomain;
import com.ftqh.core.jpa.service.BaseService;
import com.ftqh.core.web.config.StaticResourceProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import java.io.Serializable;

/**
 * Controller 常用抽象方法
 * 
 * @author ftqh
 *
 */
public abstract class AbstractController<T extends AbstractDomain<ID>, S extends BaseService<T, ID>,ID extends Serializable> {

	@Autowired
	private StaticResourceProperties staticResourceProperties;
	/**
	 * 注入Service
	 * 
	 * param service
	 * return
	 */
	@Autowired
	protected S service;
	
	/**
	 * 页面前辍，<br>
	 * domain名字
	 * 
	 * return
	 */
	protected abstract String getPagePrex();

	/**
	 * New Domain
	 * 
	 * return
	 */
	protected abstract T createDomain();

	/**
	 * 添加所需的obj到页面
	 * 
	 * param model
	 */
	protected abstract void setAttributes(ModelAndView model,T domain);
	
	
	@RequestMapping("add")
	public ModelAndView defaultNew() {
		ModelAndView model = this.getModelAndViewInstance("_edit");
		model.addObject("domain", this.createDomain());
		setAttributes(model,null);
		return model;
	}
	
	@RequestMapping(value="edit/{id}",method = RequestMethod.GET)
	public ModelAndView defaultEdit(@PathVariable ID id) {
		ModelAndView model = this.getModelAndViewInstance("_edit");
		T domain = service.findOne(id);
		model.addObject("domain", domain);
		setAttributes(model,domain);
		return model;
	}

	@RequestMapping(value="list",method = RequestMethod.GET)
	public ModelAndView defaultList(T example, @RequestParam(defaultValue="10")int page, @RequestParam(defaultValue="0")int pageSize) {
		ModelAndView model = this.getModelAndViewInstance("_list");
		Pageable pageable = new PageRequest(page, pageSize);
		Page<T> pageContent = service.findByAuto(example, pageable);
		model.addObject("pageContent", pageContent);
		setAttributes(model,null);
		return model;
	}

	protected ModelAndView getModelAndViewInstance(String viewName){
		ModelAndView modelAndView = new ModelAndView();
		modelAndView.setViewName(getPage(viewName));
		modelAndView.addObject("staticResourceUrl", staticResourceProperties.getStaticResourceUrl());
		return modelAndView;
	}
    protected String getPage(String viewName){
	    return this.getPagePrex()+viewName;
    }
}
